<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/22
 * Time: 13:48
 */

namespace common\business\employee;

use common\business\CommonHelper;
use common\business\DbHandler;
use common\consts\CommonResources;
use common\helpers\StringUtil;
use common\models\kingdee\Person;
use common\models\Log;
use Yii;
use common\business\excel\ExcelFileHandler;
use PHPExcel;
use PHPExcel_Worksheet;
use yii\db\Exception;

class EmployeeExcelFileHandler extends ExcelFileHandler
{
    /**
     * EmployeeExcelFileHandler constructor.
     */
    public function __construct($file_id)
    {
        parent::__construct($file_id);
        $this->start_row = 2;
    }

    /**
     * excel导入处理
     *
     * @param PHPExcel           $objExcel
     * @param PHPExcel_Worksheet $currentSheet
     * @param int                $startRow
     * @param int                $highestRows
     * @param callback|null      $writeBackHandler
     * @return boolean
     */
    protected function processExcel(&$objExcel, &$currentSheet, $startRow, $highestRows, $writeBackHandler = null)
    {

        try {//        找到姓名所在的列
            $colArr = [1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L',
                13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z'
            ];
            $nameColumnNo = 0;
            $employeeNumberColNo = 0;
            $idCardNumColNo = 0;
            for ($column = 1; $column <= 26; $column++) {
                $cellValue = $currentSheet->getCell($colArr[$column] . '1')->getValue();
                if (
                    $cellValue == Yii::t('app', 'Person Name') ||
                    $cellValue == Yii::t('app', 'Employee Name')
                ) {
                    $nameColumnNo = $column;
                    continue;
                }
                if (
                    $cellValue == Yii::t('app', 'Employee Number') ||
                    $cellValue == Yii::t('app', 'Employee No')
                ) {
                    $employeeNumberColNo = $column;
                    continue;
                }
                if (
                    $cellValue == Yii::t('app', 'Employee Id Card Num') ||
                    $cellValue == Yii::t('app', 'Id Card No')
                ) {
                    $idCardNumColNo = $column;
                }
            }
            if ($nameColumnNo == 0) {
                $this->addError('Process Excel', 'Employee Name Column Not Found');
                return false;
            }
            if ($employeeNumberColNo == 0) {
                $this->addError('Process Excel', 'Employee Number Column Not Found');
                return false;
            }
            if ($idCardNumColNo == 0) {
                $this->addError('Process Excel', 'Employee Id Card Num Column Not Found');
                return false;
            }
            for ($currentRow = $startRow; $currentRow <= $highestRows; $currentRow++) {
                $employeeName = $currentSheet->getCell($colArr[$nameColumnNo] . $currentRow)->getValue();
                if (StringUtil::isNullOrWhiteSpace($employeeName)) {
                    break;
                }
                $employeeNumber = $currentSheet->getCell($colArr[$employeeNumberColNo] . $currentRow)->getValue();
                $employeeIdCardNo = $currentSheet->getCell($colArr[$idCardNumColNo] . $currentRow)->getValue();

                if (StringUtil::isNullOrWhiteSpace($employeeNumber))
                    continue;

                //更新T_BD_PERSON表数据
                $personInHr = Person::findOne([
                    'FNUMBER' => $employeeNumber
                ]);

                if (!$personInHr) {
                    $this->rows_skip++;
                } else {
                    $newPerson = new Person([
                        'FNAME_L2' => $employeeName,
                        'FIDCARDNO' => $employeeIdCardNo,
                        'FNUMBER' => $employeeNumber,
                    ]);
                    $compareResult = CommonHelper::compareObjectAttributes($personInHr, $newPerson, [
                        'FNAME_L2',
                        'FIDCARDNO',
                    ]);
                    if (!$compareResult->isChanged) {
                        $this->rows_skip++;
                    } else {
                        try {
                            $newLog = new Log([
                                'action' => CommonResources::ACTION_MSG('Update', 'Person'),
                                'memo' => $compareResult->message,
                            ]);
                            //                    更新姓名
                            $personInHr->FNAME_L2 = $employeeName;
                            //                    更新身份证号码
                            $personInHr->FIDCARDNO = $employeeIdCardNo;

                            $saveIsSuccess = (new DbHandler())->saveRecordWithLogUnsafe($personInHr, $newLog);
                            if ($saveIsSuccess) {
                                $this->rows_cover++;
                            } else {
                                $this->rows_error++;
                            }
                        } catch (Exception $e) {
                            $this->rows_error++;
                        }
                    }
                }

                if ($writeBackHandler) {
                    $paramArr = [
                        'totalCount' => $this->rows_total,
                        'finishCount' => $this->rows_insert + $this->rows_cover + $this->rows_skip + $this->rows_error,
                    ];
                    call_user_func_array($writeBackHandler, $paramArr);
                }
            }
        } catch (\PHPExcel_Exception $e) {
            $errMsg = CommonHelper::getExceptionMsg($e);
            if ($writeBackHandler) {
                $paramArr = [
                    'totalCount' => $this->rows_total,
                    'finishCount' => $this->rows_insert + $this->rows_cover + $this->rows_skip + $this->rows_error,
                    'message' => $errMsg,
                ];
                call_user_func_array($writeBackHandler, $paramArr);
            }
        }

        return true;
    }
}